package com.superdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.superdp.dto.LoginFormDTO;
import com.superdp.dto.Result;
import com.superdp.dto.UserDTO;
import com.superdp.entity.User;
import com.superdp.mapper.UserMapper;
import com.superdp.service.IUserService;
import com.superdp.utils.RedisConstants;
import com.superdp.utils.RegexUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.superdp.utils.RedisConstants.LOGIN_USER_KEY;
import static com.superdp.utils.RedisConstants.LOGIN_USER_TTL;
import static com.superdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendcode(String phone) {
        //1.校验手机号
        boolean b = RegexUtils.isPhoneInvalid(phone);
        if(b){
            return Result.fail("手机号码格式不正确");
        }
        //2.生成key
        String key= RedisConstants.LOGIN_CODE_KEY+phone;
        //3.生成验证码
        String code = RandomUtil.randomNumbers(6);
        //4.存入redis
        stringRedisTemplate.opsForValue().set(key,code);
        log.debug("短信验证码发送成功，验证码为：{}",code);
        //5.设置过期时间
        stringRedisTemplate.expire(key,RedisConstants.LOGIN_CODE_TTL, TimeUnit.MINUTES);
        return Result.ok(code);
    }

    @Override
    public Result login(LoginFormDTO loginForm) {
        //1.获取参数
        String phone = loginForm.getPhone();
        String code = loginForm.getCode();
        //2.校验手机号格式
        boolean b = RegexUtils.isPhoneInvalid(phone);
        if(b){
            return Result.fail("手机号格式不正确");
        }
        //3.校验验证码
        String codeInCache = stringRedisTemplate.opsForValue().get(RedisConstants.LOGIN_CODE_KEY + phone);
        if(code==null||!codeInCache.equals(code)){
            return Result.fail("验证码错误！");
        }

        //4.查询用户是否已经注册
        User user = query().eq("phone",phone).one();
        if(user==null){
            //4.1未注册
            user = createUser(loginForm);
        }

        String token = UUID.randomUUID(true).toString();
        String key=LOGIN_USER_KEY+token;

        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        Map<String,Object> beanToMap = BeanUtil.beanToMap(userDTO, new HashMap(), CopyOptions
                .create()
                .setIgnoreNullValue(true)
                .setFieldValueEditor((FieldName, FieldValue) -> FieldValue.toString()));
        stringRedisTemplate.opsForHash().putAll(key,beanToMap);
        stringRedisTemplate.expire(key,LOGIN_USER_TTL,TimeUnit.SECONDS);
        return Result.ok(token);
    }


    private User createUser(LoginFormDTO loginForm) {
        User user = new User();
        user.setPhone(loginForm.getPhone());
        user.setNickName(USER_NICK_NAME_PREFIX+RandomUtil.randomString(8));
        save(user);
        return user;
    }
}
